package org.gokeep.communication.tcp;

import lombok.extern.slf4j.Slf4j;
import org.smartboot.socket.StateMachineEnum;
import org.smartboot.socket.extension.plugins.AbstractPlugin;
import org.smartboot.socket.transport.AioQuickClient;
import org.smartboot.socket.transport.AioSession;

import java.nio.channels.AsynchronousChannelGroup;

@Slf4j
public class ReconnectPlugin  extends AbstractPlugin {
    private final AsynchronousChannelGroup asynchronousChannelGroup;
    private final AioQuickClient client;
    private boolean shutdown = false;

    public ReconnectPlugin(AioQuickClient client) {
        this(client, null);
    }

    public ReconnectPlugin(AioQuickClient client, AsynchronousChannelGroup asynchronousChannelGroup) {
        this.client = client;
        this.asynchronousChannelGroup = asynchronousChannelGroup;
    }

    @Override
    public void stateEvent(StateMachineEnum stateMachineEnum, AioSession session, Throwable throwable) {
        if (stateMachineEnum != StateMachineEnum.SESSION_CLOSED || shutdown) {
            return;
        }
        try {
            if (asynchronousChannelGroup == null) {
                client.start();
                log.info("Client reconnection start success");
            } else {
                client.start(asynchronousChannelGroup);
                log.info("AsynchronousChannelGroup reconnection start success");
            }
        } catch (Exception e) {
            shutdown = true;
            e.printStackTrace();
        }

    }

    public void shutdown() {
        shutdown = true;
    }
}
